import { reqCode, reqLogin, reqLoginOut, reqRegisterUser, reqUserInfo } from "@/api"
import {deleteToken, getToken,setToken} from '@/until'

export default {
    state: {
        code: '',
        token: getToken(),//从localStorage中获取token
        userInfo:{}
    },
    mutations: {
        UPDATE_CODE(state,code) {
            state.code = code
        },
        UPDATE_TOKEN(state,token) {
            state.token = token
        },
        UPDATE_USERINFO(state,userInfo) {
            state.userInfo = userInfo
        },
        REMOVE_TOKEN(state) {
            state.token = ''
            state.userInfo={}
            deleteToken()
        }
    },
    actions: {
        // 获取验证码
        async getCode({ commit }, phone) {
            const res = await reqCode(phone)
            if (res.code === 200) {
                commit('UPDATE_CODE', res.data)
                return 'ok'
            } else {
                return Promise.reject('fail')
            }
        },
        // 注册用户
        async getRegisterUser({commit},paramsObj) {
            const res = await reqRegisterUser(paramsObj)
            if (res.code === 200) {
                return 'ok'
            } else {
                return Promise.reject('fail')
            }
        },
        // 登录获取token
        async getLogin({ commit }, paramsObj) {
            const res = await reqLogin(paramsObj)
            if (res.code === 200) {
                // 将token存储在localStorage中，避免一刷新token就没有了
                setToken(res.data.token)
                // localStorage.setItem('token', res.data.token)
                commit('UPDATE_TOKEN',res.data.token)
            }
        },
        // 获取用户信息
        async getUserInfo({commit}) {
            const res = await reqUserInfo()
            if (res.code === 200) {
                commit('UPDATE_USERINFO',res.data)
            } else {
                return Promise.reject('fail')
            }
        },
        // 退出登录
        async getLoginOut({commit}) {
            const res = await reqLoginOut()
            if (res.code === 200) {
                commit('REMOVE_TOKEN')
                return 'ok'
            } else {
                return Promise.reject('fail')
            }
        }
    },
    getters: {
        
    }
}